package com.xy.exam.controller;

import com.xy.exam.entity.Product;
import com.xy.exam.service.ProductService;
import com.xy.exam.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:徐莹
 * @Date:2025/04/14
 * 商品控制器
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根据ID查询商品
     */
    @GetMapping("/{id}")
    public ResponseResult<Product> getProductById(@PathVariable int id) {
        Product product = productService.findProductById(id);
        if (product != null) {
            return ResponseResult.success(product);
        } else {
            return ResponseResult.error("商品不存在");
        }
    }

    /**
     * 添加商品
     */
    @PostMapping
    public ResponseResult<Product> addProduct(@RequestBody Product product) {
        try {
            Product addedProduct = productService.addProduct(product);
            return ResponseResult.success("添加商品成功", addedProduct);
        } catch (Exception e) {
            return ResponseResult.error("添加商品失败：" + e.getMessage());
        }
    }

    /**
     * 更新商品
     */
    @PutMapping
    public ResponseResult<Product> updateProduct(@RequestBody Product product) {
        try {
            Product updatedProduct = productService.updateProduct(product);
            return ResponseResult.success("更新商品成功", updatedProduct);
        } catch (Exception e) {
            return ResponseResult.error("更新商品失败：" + e.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteProduct(@PathVariable int id) {
        try {
            productService.deleteProduct(id);
            return ResponseResult.success("删除商品成功", null);
        } catch (Exception e) {
            return ResponseResult.error("删除商品失败：" + e.getMessage());
        }
    }
} 